import { CHAT_PARAMETERS_CACHE_KEY } from "@shared/constants";
import type { ThreadFormChatParameters } from "@shared/triplit/types";
import { threadFormsQueries } from "../definitions/thread-forms-queries";
import type { QueryOneConfig, QueryResult } from "../types";
import { useStandardQueryOne } from "./use-standard-query";

export function useChatParametersByThreadId(
  threadId: string | null,
  config?: QueryOneConfig<"threadForms">,
): QueryResult<ThreadFormChatParameters> {
  const queryThreadId = threadId ?? CHAT_PARAMETERS_CACHE_KEY;

  return useStandardQueryOne(
    () => threadFormsQueries.byThreadId(queryThreadId),
    {
      ...config,
      enabled: !!queryThreadId && config?.enabled !== false,
      select: (data) => {
        if (!data) return null;
        const p = data.chatParameters ?? {};
        const normalized = Object.fromEntries(
          Object.entries(p).map(([k, v]) => [k, v === undefined ? null : v]),
        ) as ThreadFormChatParameters;
        return normalized;
      },
    },
  );
}
